package com.ubb.dbms.core.fileManagers.indexFileManager;

import static com.ubb.dbms.core.fileManagers.binaryFileManager.BinaryFileUtils.offsetToRowNr;
import static com.ubb.dbms.core.fileManagers.binaryFileManager.BinaryFileUtils.rowNrToOffset;

import java.nio.ByteBuffer;

import com.ubb.dbms.core.fileManagers.binaryFileManager.BinaryFileIO;
import com.ubb.dbms.core.fileManagers.indexFileManager.bPlusTree.Node;
import com.ubb.dbms.core.fileManagers.indexFileManager.bPlusTree.NodeConverter;

public class IndexFileIO extends BinaryFileIO {

	public IndexFileIO(String fileName, String rsFileName, int headerLength,
			int rowLength) {
		super(fileName, rsFileName, headerLength, rowLength, true);
	}

	public void updateHeader(int rowNr) {
		super.handleUpdateHeader(ByteBuffer.allocate(headerLength).putInt(rowNr).array());
	}
	
	public int readFileHeader() {
		byte[] header = super.handleReadFileHeader();
		return ByteBuffer.wrap(header, 0, headerLength).getInt();
	}
	
	public Node readRow(int rowNr) {
		int nodeOffset = rowNrToOffset(rowNr, headerLength, rowLength);
		byte[] row = super.handleReadRow(nodeOffset);
		return NodeConverter.toNode(row, rowNr, this);
	}

	public int insertRow(Node node) {
		byte[] row = NodeConverter.toByteArray(node, rowLength);
		int offsetInFile = super.handleInsertRow(row);
		int rowNr = offsetToRowNr(offsetInFile, headerLength, rowLength);
		return rowNr;
	}

	public void updateRow(Node node, int rowNr) {
		byte[] row = NodeConverter.toByteArray(node, rowLength);
		int nodeOffset = rowNrToOffset(rowNr, headerLength, rowLength);
		super.handleUpdateRow(row, nodeOffset);
	}
}
